package com.dujiu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dujiu.config.JwtConfig;
import com.dujiu.mapper.UserMapper;
import com.dujiu.pojo.dto.LoginFormDTO;
import com.dujiu.pojo.entity.User;
import com.dujiu.pojo.vo.UserVO;
import com.dujiu.result.Result;
import com.dujiu.service.IUserService;
import com.dujiu.utils.JwtUtil;
import com.dujiu.utils.PhoneUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.dujiu.constant.LoginConstant.*;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private JwtConfig jwtConfig;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送手机验证码
     * @param phone
     * @return
     */
    @Override
    public Result sendCode(String phone) {
        log.info("进入的手机号为：{}",phone);
        // 校验手机号
        if (PhoneUtil.isValidPhone(phone)) {
            return Result.fail("手机号格式有误！");
        }

        // 随机生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 保存验证码到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);

        // 发送验证码
        log.info("发送短信验证码成功，验证码：{}", code);
        return Result.ok();
    }

    /**
     * 用户登录
     * @param loginFormDTO
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginFormDTO) {
        String phone = loginFormDTO.getPhone();
        String code = loginFormDTO.getCode();

        // 判断手机号格式是否有误
        if (PhoneUtil.isValidPhone(phone)) {
            return Result.fail("手机号格式有误！");
        }

        String redisCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (redisCode == null || !redisCode.equals(code)) {
            return Result.fail("验证码错误，请检查！");
        }

        User user = query().eq("phone", phone).one();
        if (user == null) {
            user = registerUserByPhone(phone);
        }

        String token = jwtUtil.createToken(user);
        System.out.println(token);
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userVO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue == null ? null : fieldValue.toString()));
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        // 设置token过期时间
        stringRedisTemplate.expire(tokenKey,jwtConfig.getTokenTime(),TimeUnit.MILLISECONDS);
        log.debug("登录成功，用户id为：{}",user.getUserId());
        // 成功后，删除验证码
        stringRedisTemplate.delete(LOGIN_CODE_KEY + phone);
        return Result.ok(token);
    }

    // 注册
    private User registerUserByPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setUsername("dujiu_" + RandomUtil.randomNumbers(6));

        // 为新用户设置性别和密码的默认值
        user.setSex("male");
        user.setPassword("123456");
        save(user);
        return user;
    }
}


